﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace RailwayReservationWeb.manager
{
    public partial class train_add : System.Web.UI.Page
    {
        private RailwayReservationDataContext db;

        protected void Page_Load(object sender, EventArgs e)
        {
            db = new RailwayReservationDataContext();
            pMessage.Visible = false;
            if (!IsPostBack)
            {
                BindTrainType();
                AutoFillCompatments();
            }
        }

        private void BindTrainType()
        {
            cboTrainType.DataSource = db.TrainTypes;
            cboTrainType.DataTextField = "TrainTypeName";
            cboTrainType.DataValueField = "TrainTypeId";
            cboTrainType.DataBind();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    AutoFillCompatments();
                    var ob = new Train();
                    ob.TrainNo = Int32.Parse(txtTrainNo.Text.Trim());
                    ob.TrainName = txtTrainName.Text.Trim();
                    ob.TrainTypeId = Int32.Parse(cboTrainType.SelectedValue.Trim());
                    ob._1AC = Int16.Parse(txt1AC.Text.Trim());
                    ob._2AC = Int16.Parse(txt2AC.Text.Trim());
                    ob._3AC = Int16.Parse(txt3AC.Text.Trim());
                    ob.Sleeper = Int16.Parse(txtSleeper.Text.Trim());
                    ob.General = Int16.Parse(txtGeneral.Text.Trim());
                    ob.Status = 1;
                    db.Trains.InsertOnSubmit(ob);
                    db.SubmitChanges();
                    Response.Redirect("~/manager/train_list.aspx");
                }
            }
            catch (Exception ex)
            {
                ShowMessage(ex.Message);
            }
        }

        private void AutoFillCompatments()
        {
            if (String.IsNullOrWhiteSpace(txt1AC.Text)) { txt1AC.Text = "0"; }
            if (String.IsNullOrWhiteSpace(txt2AC.Text)) { txt2AC.Text = "0"; }
            if (String.IsNullOrWhiteSpace(txt3AC.Text)) { txt3AC.Text = "0"; }
            if (String.IsNullOrWhiteSpace(txtSleeper.Text)) { txtSleeper.Text = "0"; }
            if (String.IsNullOrWhiteSpace(txtGeneral.Text)) { txtGeneral.Text = "0"; }
        }

        private void ShowMessage(string msg)
        {
            pMessage.Visible = true;
            pMessage.InnerText = msg;
        }
    }
}
